<script setup lang="ts" name="budget">
import { ref } from 'vue';
import { getYear } from '@/hooks/useDate';
import { ExeBudgetScoreVO, ScoreQueryDTO } from '@/api/fill/execute/budget-total/Types';
import { getListAll } from '@/api/fill/execute/budget-total';
import { globalHeaders } from '@/utils/request';
import { useTableHeight } from '@/hooks/useMethod';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(true);
const showSearch = ref(true);

const queryFormRef = ref<ElFormInstance>();

//查询参数
const queryParams = ref<ScoreQueryDTO>({
  year: getYear()
});

/*用于存储表格数据*/
const tableList = ref<ExeBudgetScoreVO[]>([]);

/*全部列表查询*/
const getList = () => {
  getListAll(queryParams.value)
    .then((res) => {
      tableList.value = res.data;
      // console.log('数据：', res.data);
    })
    .finally(() => {
      loading.value = false;
    });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    year: getYear()
  };

  handleQuery();
};
/*====================================================================导入、导出========================================================================*/
/** 导出模板按钮操作 */
const importTemplate = () => {
  proxy?.download(
    '/exe/BudgetScore/importTemplate',
    {
      ...queryParams.value
    },
    `预算总分模板.xlsx`
  );
};

const uploadRef = ref<ElUploadInstance>();
/*** 导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: 0,
  //年份
  year: queryParams.value.year,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/exe/BudgetScore/importData'
});
/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '导入预算总分';
  upload.open = true;
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;color: #00cd00'>" + response.msg + '</div>',
    '导入结果',
    {
      dangerouslyUseHTMLString: true
    }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}


const tableStyle = useTableHeight(showSearch);
/*挂载生命周期钩子*/
onMounted(() => {
  getList();
});
</script>

<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"  :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <div>
            <el-form ref="queryFormRef" :inline="true">
              <el-form-item label="年份" prop="year">
                <el-date-picker type="year" format="YYYY" value-format="YYYY" v-model="queryParams.year" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div class="header-container">
          <div>
            <el-button type="success" icon="Upload" v-hasPermi="['exe:budgetScore:import']" @click="handleImport">导入</el-button>
            <el-button type="warning" icon="Download" @click="importTemplate" v-hasPermi="['exe:budgetScore:expot']">导出模板</el-button>
          </div>

          <div class="budget-header">{{ queryParams.year }}年预算总分</div>

          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </div>
      </template>
      <div class="table-class">
        <el-table ref="tableRef" :data="tableList" :style="tableStyle" border append class="custom-table enhanced-table">
          <el-table-column prop="deptName" label="预算部门" align="center" width="240" show-overflow-tooltip fixed />
          <el-table-column prop="exeDeviationRate" label="预算执行偏差率" align="center" width="150" />
          <el-table-column prop="processControl" label="预算过程控制" align="center" width="150" />
          <el-table-column prop="compTimeliness" label="完整、及时性" align="center" width="150" />
          <el-table-column prop="annualRushExpenditure" label="年度突击开支" align="center" width="150" />
          <el-table-column prop="illegalViolations" label="违法违规现象" align="center" width="150" />
          <el-table-column prop="extraBudgetary" label="预算外事项" align="center" width="150" />
          <el-table-column prop="excessAnnualCost" label="超年度成本费用预算额" align="center" width="180" />
          <el-table-column prop="budgetManageBonus" label="预算管理加分项" align="center" width="150" />
          <el-table-column prop="totalScore" label="合计得分" align="center" width="150" />
          <el-table-column prop="processControlAdjust" label="预算过程控制调整分" align="center" width="165" />
          <el-table-column prop="controlAdjustScore" label="得分(预算过程控制调整后)" align="center" width="220" />
          <el-table-column prop="proposedScore" label="拟扣分（调整后）" align="center" width="150" />
          <el-table-column prop="reviewedDeductionScore" label="审定扣分" align="center" width="150" />
          <el-table-column prop="reviewedScore" label="审定得分" align="center" width="150" />
          <el-table-column prop="remarks" label="备注" align="center" width="350" show-overflow-tooltip />
        </el-table>
      </div>
    </el-card>

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" style="width: 450px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?year=' + upload.year"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div style="margin-top: 10px; color: red; font-size: 15px">* 仅允许导入xls、xlsx格式文件</div>
            <el-link type="primary" :underline="false" style="font-size: 14px; vertical-align: baseline; margin-top: 10px" @click="importTemplate">
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
/* 核心布局样式 */
.header-container {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between; /* 左右贴边 */
  gap: 16px; /* 添加子元素间距 */
}

.budget-header {
  flex: 1; /* 占据剩余空间 */
  text-align: center; /* 文字水平居中 */
  white-space: nowrap; /* 防止标题换行 */
  font-size: 28px;
  font-weight: bold;
}

/* 可选：确保按钮组和工具栏不换行 */
.header-container > div:first-child,
.right-toolbar {
  flex-shrink: 0; /* 防止内容压缩 */
}
</style>
